<template>
  <div class="dashboard-container">
    <div class="page-header">
      <h1>患者概述</h1>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索患者姓名"
          :prefix-icon="Search"
          clearable
          @clear="handleSearch"
          @input="handleSearch"
        >
        </el-input>
        <el-button type="primary" @click="handleAddPatient">
          <el-icon><Plus /></el-icon>添加患者
        </el-button>
      </div>
    </div>

    <el-row :gutter="20" class="dashboard-stats">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-icon" style="background-color: #67C23A;">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.totalPatients }}</div>
            <div class="stat-label">总患者数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-icon" style="background-color: #F56C6C;">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.abnormalPatients }}</div>
            <div class="stat-label">异常患者</div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-icon" style="background-color: #E6A23C;">
            <el-icon><Male /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.malePatients }}</div>
            <div class="stat-label">男性患者</div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-icon" style="background-color: #409EFF;">
            <el-icon><Female /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.femalePatients }}</div>
            <div class="stat-label">女性患者</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-card class="patient-list-card">
      <template #header>
        <div class="card-header">
          <span>患者列表</span>
          <div class="header-actions">
            <el-select v-model="filterStatus" placeholder="健康状态" @change="handleFilterChange">
              <el-option label="全部" value="" />
              <el-option label="正常" value="0" />
              <el-option label="异常" value="1" />
            </el-select>
    
          </div>
        </div>
      </template>

      <el-table :data="patientsList" style="width: 100%" v-loading="loading" @row-click="handleRowClick">
        <el-table-column label="患者信息" min-width="200">
          <template #default="scope">
            <div class="patient-info">
              <div>
                <div class="patient-name">{{ scope.row.name }}</div>
                <div class="patient-id">ID: {{ scope.row.id }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column label="性别" width="80">
          <template #default="scope">
            {{ scope.row.gender === 0 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="contact" label="联系方式" width="150" />
        <el-table-column label="健康状态" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.patientStatus === 0 ? 'success' : 'danger'">
              {{ scope.row.patientStatus === 0 ? '正常' : '异常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="入院日期" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.admissionDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click.stop="handleViewDetails(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click.stop="handleEditPatient(scope.row)">编辑</el-button>
            <el-dropdown @command="(command) => handleMoreActions(command, scope.row)" trigger="click">
              <el-button size="small" @click.stop>
                更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="diagnosis">诊断记录</el-dropdown-item>
                  <el-dropdown-item command="livingWill">医嘱管理</el-dropdown-item>
                  <el-dropdown-item command="medicalRecords">病情记录</el-dropdown-item>
                  <el-dropdown-item divided command="delete" style="color: #F56C6C;">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑患者对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
    >
      <el-form ref="patientFormRef" :model="patientForm" :rules="patientRules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="patientForm.name" placeholder="请输入患者姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="patientForm.gender">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="patientForm.age" :min="0" :max="150" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="patientForm.contact" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="健康状态" prop="patientStatus">
          <el-radio-group v-model="patientForm.patientStatus">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">异常</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      title="删除确认"
      v-model="deleteDialogVisible"
      width="300px"
    >
      <div class="delete-confirm">
        <el-icon class="warning-icon"><Warning /></el-icon>
        <p>确定要删除该患者吗？此操作不可恢复。</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定删除</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, 
  Plus, 
  Search, 
  Warning, 
  ArrowDown, 
  Male, 
  Female 
} from '@element-plus/icons-vue'
import { 
  listPatients, 
  getPatients, 
  addPatients, 
  updatePatients, 
  delPatients 
} from '@/api/patients'

const router = useRouter()

// 查询参数
const queryParams = reactive({
  name: '',
  contact: '',
  patientStatus: ''
})

// 统计数据
const stats = reactive({
  totalPatients: 0,
  abnormalPatients: 0,
  malePatients: 0,
  femalePatients: 0
})

// 患者列表数据
const patientsList = ref([])
const total = ref(0)
const loading = ref(false)
const searchQuery = ref('')
const filterStatus = ref('')
const sortBy = ref('recent')

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const patientForm = reactive({
  id: null,
  name: '',
  gender: 0,
  age: 0,
  contact: '',
  patientStatus: 0,
  admissionDate: null
})
const patientFormRef = ref(null)
const patientRules = {
  name: [{ required: true, message: '请输入患者姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  contact: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  patientStatus: [{ required: true, message: '请选择健康状态', trigger: 'change' }]
}

// 删除相关
const deleteDialogVisible = ref(false)
const patientToDelete = ref(null)

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取患者列表
const getPatientList = async () => {
  loading.value = true
  try {
    // 构建查询参数，只传入非空值
    const query = {}
    if (queryParams.name) {
      query.name = queryParams.name
    }
    if (queryParams.patientStatus !== '') {
      query.patientStatus = queryParams.patientStatus
    }
    
    const response = await listPatients(query)
    patientsList.value = response
    total.value = response.length
    
    // 更新统计数据
    stats.totalPatients = response.length
    stats.abnormalPatients = response.filter(p => p.patientStatus === 1).length
    stats.malePatients = response.filter(p => p.gender === 0).length
    stats.femalePatients = response.filter(p => p.gender === 1).length
  } catch (error) {
    console.error('获取患者列表失败:', error)
    ElMessage.error('获取患者列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  // 只根据姓名搜索
  queryParams.name = searchQuery.value
  getPatientList()
}

// 处理过滤变化
const handleFilterChange = () => {
  queryParams.patientStatus = filterStatus.value
  getPatientList()
}

// 处理排序变化
const handleSortChange = () => {
  // 前端排序
  if (sortBy.value === 'name') {
    patientsList.value.sort((a, b) => a.name.localeCompare(b.name))
  } else if (sortBy.value === 'age') {
    patientsList.value.sort((a, b) => a.age - b.age)
  } else if (sortBy.value === 'recent') {
    patientsList.value.sort((a, b) => new Date(b.admissionDate) - new Date(a.admissionDate))
  }
}

// 重置表单
const resetForm = () => {
  patientForm.id = null
  patientForm.name = ''
  patientForm.gender = 0
  patientForm.age = 0
  patientForm.contact = ''
  patientForm.patientStatus = 0
  patientForm.admissionDate = null
}

// 处理添加患者
const handleAddPatient = () => {
  resetForm()
  dialogTitle.value = '添加患者'
  dialogVisible.value = true
}

// 处理编辑患者
const handleEditPatient = async (patient) => {
  resetForm()
  dialogTitle.value = '编辑患者'
  
  try {
    const response = await getPatients(patient.id)
    Object.assign(patientForm, response)
    dialogVisible.value = true
  } catch (error) {
    console.error('获取患者详情失败:', error)
    ElMessage.error('获取患者详情失败')
  }
}

// 提交表单
const submitForm = () => {
  patientFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (patientForm.id) {
          // 编辑患者
          await updatePatients(patientForm)
          ElMessage.success('更新患者成功')
        } else {
          // 添加患者
          await addPatients(patientForm)
          ElMessage.success('添加患者成功')
        }
        dialogVisible.value = false
        getPatientList()
      } catch (error) {
        console.error('保存患者信息失败:', error)
        ElMessage.error('保存患者信息失败')
      }
    }
  })
}

// 处理查看详情
const handleViewDetails = (patient) => {
  // 跳转到患者详情页
  router.push(`/diagnosis?patientId=${patient.id}`)
}

// 处理更多操作
const handleMoreActions = (command, patient) => {
  switch (command) {
    case 'diagnosis':
      router.push(`/diagnosis?patientId=${patient.id}`)
      break
    case 'livingWill':
      router.push(`/living-will?patientId=${patient.id}`)
      break
    case 'medicalRecords':
      router.push(`/medical-records?patientId=${patient.id}`)
      break
    case 'delete':
      patientToDelete.value = patient
      deleteDialogVisible.value = true
      break
  }
}

// 确认删除
const confirmDelete = async () => {
  if (patientToDelete.value) {
    try {
      await delPatients(patientToDelete.value.id)
      ElMessage.success('删除患者成功')
      deleteDialogVisible.value = false
      getPatientList()
    } catch (error) {
      console.error('删除患者失败:', error)
      ElMessage.error('删除患者失败')
    }
  }
}

// 处理行点击
const handleRowClick = (row) => {
  handleViewDetails(row)
}

// 生命周期钩子
onMounted(() => {
  getPatientList()
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
  min-width: 200px;
  justify-content: flex-end;
}

.dashboard-stats {
  margin-bottom: 24px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  margin-bottom: 20px;
}

.stat-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 16px;
  color: white;
  font-size: 24px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  line-height: 1.2;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.patient-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.patient-info {
  display: flex;
  align-items: center;
}

.patient-name {
  font-weight: bold;
  font-size: 14px;
  color: #303133;
}

.patient-id {
  font-size: 12px;
  color: #909399;
}

.delete-confirm {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.warning-icon {
  font-size: 32px;
  color: #F56C6C;
  margin-bottom: 10px;
}
</style> 